package softwaredepartment.zxit.com.pt_3280cinandroid.Service;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;

import com.socks.library.KLog;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class IsCallMeService extends Service {

    private final IBinder iBinder = new I$CallYouBinder();
    public static int STATE_CALL = 0;

    public IsCallMeService() {
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        KLog.i("LOG", "onStartCommand()");
        StartCallMeCheckedThread();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        KLog.i("LOG", "onBind()");
        return iBinder;
    }


    public class I$CallYouBinder extends Binder {
        public IsCallMeService getService() {
            return IsCallMeService.this;
        }


    }

    public void StartCallMeCheckedThread() {
        Thread thread = new Thread(new CallingMeChecked());
        thread.start();
    }

    public class CallingMeChecked implements Runnable {

        public List<Socket> socketList = Collections.synchronizedList(new ArrayList<Socket>());


        @Override
        public void run() {
//            Intent itt = new Intent("com.zxIT.softDepartment.broadcast.beCall");
//            sendBroadcast(itt);


            try {
                ServerSocket ss = new ServerSocket(30000);
                while (true) {
                    KLog.i("LOG", "正在监听30000端口是否有信息。");
                    Socket s = ss.accept();
                    BufferedReader Br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    PrintStream ps = new PrintStream(s.getOutputStream());
                    String CIp= Br.readLine();
                    SharedPreferences sharedPreferences = getSharedPreferences("CallEachOtherBasicInfo",
                            Activity.MODE_PRIVATE);
                    // 使用getString方法获得value，注意第2个参数是value的默认值
                    String NOW_STATE = sharedPreferences.getString("NOW_STATE", null);
                    String CLIENT_IP = sharedPreferences.getString("CLIENT_IP", null);
                    if (NOW_STATE.equals("1")) {
                        if(CLIENT_IP.equals(CIp)){
                            //查看计时器时间如果超出30s表示未接通将状态重置为0，清除CLIENT_IP
                        }else{
                            ps.println("'result':{'code':'001',info:'正忙！请稍后再试。'}");
                        }
                    }
                    if(NOW_STATE.equals("0")){
                        //实例化SharedPreferences.Editor对象（第二步）
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        //用putString的方法保存数据
                        editor.putString("CLIENT_IP", CIp);
                        editor.putString("NOW_STATE","1");
                        //提交当前数据
                        editor.commit();
                        Intent it = new Intent("com.zxIT.softDepartment.broadcast.beCall");
                        sendBroadcast(it);
                        ps.println("'result':{'code':'000',info:'正在等待确认。'}");
                        timeVoid();
                    }
                    if(NOW_STATE.equals("2")){
                        if(CLIENT_IP.equals(CIp)){
                            ps.println("'result':{'code':'002',info:'正在通话。'}");

                        }else{
                            ps.println("'result':{'code':'001',info:'正忙！请稍后再试。'}");
                        }
                    }
                    if(NOW_STATE.equals("3")){
                        //实例化SharedPreferences.Editor对象（第二步）
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        //用putString的方法保存数据
                        editor.putString("CLIENT_IP", "");
                        editor.putString("NOW_STATE","0");
                        //提交当前数据
                        editor.commit();
                        ps.println("'result':{'code':'003',info:'通话结束。'}");
                        timeVoid();
                    }
                    ps.close();
                    s.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public void timeVoid(){
        final Timer timer = new Timer();
        TimerTask tt=new TimerTask() {
            @Override
            public void run() {
                SharedPreferences sharedPreferences = getSharedPreferences("CallEachOtherBasicInfo",
                        Activity.MODE_PRIVATE);
                if(sharedPreferences.getString("NOW_STATE", null).equals("1")){
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    //用putString的方法保存数据
                    editor.putString("CLIENT_IP", null);
                    editor.putString("NOW_STATE","0");
                    //提交当前数据
                    editor.commit();
                    Intent it = new Intent("com.zxIT.softDepartment.broadcast.beCallCancel");
                    sendBroadcast(it);
                }
                timer.cancel();
            }
        };
        timer.schedule(tt, 15000);
    }
}
